import { TransPack } from "./common/TransPack";
import { BaseClient } from "./BaseClient";
import { ClientMsg } from "./common/ClientMsg";
import { ELogLevel } from "./common/ELogLevel";
import { BaseMsgHandler } from "./BaseMsgHandler";
import { LTLogger } from "./logger/LTLogger";

export class BaseServer {

    /**
     * -1代表不更新
     * >=0 代表更新间隔(ms)
     */
    public updateTime: number = -1;

    /**
     * 最大执行时间,ms
     */
    public maxDealTime: number = 1000;

    /**
     * tag
     */
    public tag: string = "BaseServer";

    protected _logLevel: ELogLevel = ELogLevel.Log;

    public logger: LTLogger;

    protected _lastUpdateTime: number;

    protected _msgQueen: ClientMsg[];

    protected _msgHandleMap: Map<number, BaseMsgHandler<BaseServer>>;

    public async Init() {
        this.logger = new LTLogger(this.tag, this._logLevel);
        this.Log("开始执行初始化");
        this._msgQueen = [];
        this._lastUpdateTime = 0;
        this._msgHandleMap = new Map<number, BaseMsgHandler<BaseServer>>();
        await this._OnInit();
        this.Log("初始化完成");
    }

    protected async _OnInit() {
    }

    protected _RegistMsgHandle(handle: BaseMsgHandler<BaseServer>) {
        if (handle.msgId == null) {
            this.Log("_RegistMsgHandle:msgId为空", ELogLevel.Error);
            return;
        }
        if (this._msgHandleMap.has(handle.msgId)) {
            this.Log("_RegistMsgHandle:msgId已注册," + handle.msgId, ELogLevel.Error);
            return;
        }
        this._msgHandleMap.set(handle.msgId, handle);
        this.Log("_RegistMsgHandle: msgId: " + handle.msgId + " 注册成功");
    }

    public LogicUpdate() {
        if (this.updateTime < 0) return;
        let nowTime = Date.now();
        let passTick = nowTime - this._lastUpdateTime;
        if (passTick < this.updateTime) {
            return;
        }
        this._lastUpdateTime = nowTime;

        this.Log("开始执行消息处理逻辑", ELogLevel.Debug);
        let count: number = 0;
        while (this._msgQueen.length > 0) {
            let msg = this._msgQueen.shift();
            this._HandleMsg(msg);
            count++;

            let timeOffset = Date.now() - nowTime;
            if (timeOffset > this.maxDealTime) {
                this.Log("已达到最大执行时间,强制跳出,已执行:" + count + "条数据")
                break;
            }
        }
        this.Log("消息处理逻辑执行完成", ELogLevel.Debug);

        this._OnLogicUpdate();
    }

    protected _HandleMsg(msg: ClientMsg) {
        this.Log('开始处理消息:' + msg.transData.type, ELogLevel.Debug);
        let searchHandle = this._msgHandleMap.get(msg.transData.type);
        if (searchHandle == null) {
            this.Log('无消息处理器:' + msg.transData.type, ELogLevel.Warn);
            return;
        }
        searchHandle.HandleMsg(msg);
        this.Log('消息:' + msg.transData.type + '处理完成', ELogLevel.Debug);
    }

    protected _OnLogicUpdate() {

    }

    public ClientPushMsg(msg: TransPack, client: BaseClient) {
        this._msgQueen.push(new ClientMsg(msg, client));
    }

    public Log(str: string, level: ELogLevel = ELogLevel.Log) {
        this.logger.Log(str, level);
    }

}